# -*- coding:UTF-8 -*- ＃
#!/usr/bin/python
'''
Created on 2013-4-23

@author: Administrator
'''
from PIL import Image
import sys,os
from com.xdtech.python.util import PathUtil
from rules import config

def listFile(folder):
    "遍历文件夹"
    for item in os.listdir(folder):
        path = os.path.join(folder,item)
        if os.path.isdir(path) :
            listFile(path)
        else :
            fileName,ext = os.path.splitext(path)
            if path.find("_thumb") == -1 and not os.path.exists(fileName + "_thumb" + ext):
                print("处理图片:" + path)
                resizeImage(path);
        
def resizeImage(filePath):
    "生成缩略图"
    try:
        img = Image.open(filePath,'r')
        sizes = compRadio(img.size)
        newImg = img.resize((sizes[0],sizes[1]),Image.ANTIALIAS)
        fileName,ext = os.path.splitext(filePath)
        print(img.mode);
        newImg = newImg.convert("RGB");
        fileName = fileName + "_thumb" + ext.strip()
        newImg.save(fileName)
    except IOError:
        print("无法处理图片:" + filePath)
        print(sys.exc_info()[0],sys.exc_info()[1])
    except KeyError:
        print("无法处理图片:" + filePath)
        print(sys.exc_info()[0],sys.exc_info()[1])

def compRadio(sizes):#(2687, 2382)
    newWidth = 197
    newHeight = 104
    if sizes[0] <= newWidth and sizes[1] <= newHeight:
        return sizes
    radio = float(sizes[0])/float(sizes[1])
    if sizes[0] > sizes[1] : #横图
        height = newWidth / radio
        if height <= newHeight :
            newHeight = height
        else:
            newWidth = newHeight * radio
    else : #竖图或正方
        width = newHeight * radio
        if width <= newWidth :
            newWidth = width
        else:
            newHeight = newWidth / radio

    return (int(newWidth),int(newHeight))
        
    
if __name__ == '__main__':
    #print(sys.argv[1])
    #listFile(sys.argv[1])
    print(config.load())
